package com.xunyun.kotlinwc.main.repository

import android.annotation.SuppressLint
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.xunyun.kotlinwc.main.api.MainService
import com.xunyun.kotlinwc.main.model.BannerBean
import com.xunyun.kotlinwc.network.RetrofitHolder
import com.xunyun.kotlinwc.network.exception.ApiException
import com.xunyun.kotlinwc.network.exception.ErrorConsumer
import com.xunyun.kotlinwc.network.lifecycle.RxLifeCycle
import com.xunyun.kotlinwc.network.response.ResponseTransformer
import io.reactivex.functions.Consumer

/**
 * @author gl
 * @date 2021/9/8
 * @desc
 */
class MainRepository {

    companion object {
        private var instance: MainRepository? = null
            get() {
                if (field == null) {
                    field = MainRepository()
                }
                return field
            }

        @Synchronized
        fun get(): MainRepository {
            return instance!!
        }
    }


    @SuppressLint("CheckResult")
    fun getBannerData(
        lifecycleOwner: LifecycleOwner,
        bannerListLiveData: MutableLiveData<List<BannerBean>>
    ) {
        RetrofitHolder.singleton.getRetrofit()
            .create(MainService::class.java)
            .getBannerData()
            .compose(ResponseTransformer())
            .compose(RxLifeCycle(lifecycleOwner))
            .subscribe(Consumer {
                bannerListLiveData.value = it?.run {
                    this
                }


            }, object : ErrorConsumer() {
                override fun error(apiException: ApiException?) {

                }

            })

    }

}


